<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="通道名称" prop="channelName">
        <el-input
          v-model="queryParams.channelName"
          placeholder="请输入通道名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通道类型" prop="channelType">
        <el-select v-model="queryParams.channelType" placeholder="请选择通道类型" clearable>
          <el-option label="免费通道" value="free" />
          <el-option label="付费通道" value="paid" />
          <el-option label="混合通道" value="mixed" />
        </el-select>
      </el-form-item>
      <el-form-item label="显示状态" prop="isVisible">
        <el-select v-model="queryParams.isVisible" placeholder="请选择显示状态" clearable>
          <el-option label="显示" :value="1" />
          <el-option label="隐藏" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['video:channel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['video:channel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['video:channel:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="channelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="通道ID" align="center" prop="channelId" width="80" />
      <el-table-column label="通道图标" align="center" width="80">
        <template slot-scope="scope">
          <span style="font-size: 32px;">{{ scope.row.channelIcon }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通道名称" align="center" prop="channelName" :show-overflow-tooltip="true" />
      <el-table-column label="副标题" align="center" prop="channelSubtitle" :show-overflow-tooltip="true" />
      <el-table-column label="通道类型" align="center" prop="channelType" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.channelType === 'free'" type="success">免费</el-tag>
          <el-tag v-else-if="scope.row.channelType === 'paid'" type="warning">付费</el-tag>
          <el-tag v-else type="info">混合</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" width="80" />
      <el-table-column label="视频数" align="center" prop="videoCount" width="80" />
      <el-table-column label="播放量" align="center" prop="totalViews" width="100">
        <template slot-scope="scope">
          {{ formatNumber(scope.row.totalViews) }}
        </template>
      </el-table-column>
      <el-table-column label="收入" align="center" prop="totalRevenue" width="100">
        <template slot-scope="scope">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ scope.row.totalRevenue }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示状态" align="center" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isVisible"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['video:channel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-connection"
            @click="handleBindCategory(scope.row)"
            v-hasPermi="['video:channel:edit']"
          >绑定分类</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['video:channel:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通道对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="通道名称" prop="channelName">
          <el-input v-model="form.channelName" placeholder="请输入通道名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="通道副标题" prop="channelSubtitle">
          <el-input v-model="form.channelSubtitle" placeholder="请输入通道副标题" maxlength="100" />
        </el-form-item>
        <el-form-item label="通道描述" prop="channelDescription">
          <el-input v-model="form.channelDescription" type="textarea" placeholder="请输入通道描述" maxlength="200" />
        </el-form-item>
        <el-form-item label="通道图标" prop="channelIcon">
          <el-select v-model="form.channelIcon" placeholder="请选择通道图标">
            <el-option label="💜 紫色爱心" value="💜" />
            <el-option label="💛 黄色爱心" value="💛" />
            <el-option label="💚 绿色爱心" value="💚" />
            <el-option label="🧡 橙色爱心" value="🧡" />
            <el-option label="❤️ 红色爱心" value="❤️" />
            <el-option label="💙 蓝色爱心" value="💙" />
            <el-option label="🎬 电影" value="🎬" />
            <el-option label="🎥 摄像机" value="🎥" />
            <el-option label="📺 电视" value="📺" />
            <el-option label="🎭 面具" value="🎭" />
          </el-select>
        </el-form-item>
        <el-form-item label="通道类型" prop="channelType">
          <el-radio-group v-model="form.channelType">
            <el-radio label="free">免费通道</el-radio>
            <el-radio label="paid">付费通道</el-radio>
            <el-radio label="mixed">混合通道</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序权重" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" :max="999" />
          <span style="color: #909399; font-size: 12px; margin-left: 10px;">数字越大越靠前</span>
        </el-form-item>
        <el-form-item label="显示状态" prop="isVisible">
          <el-radio-group v-model="form.isVisible">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定分类对话框 -->
    <el-dialog title="绑定分类" :visible.sync="bindOpen" width="900px" append-to-body>
      <div style="margin-bottom: 20px;">
        <el-alert
          :title="`为通道「${currentChannel.channelName}」绑定分类`"
          type="info"
          :closable="false"
          show-icon>
        </el-alert>
      </div>
      
      <!-- 统计信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-card shadow="hover">
            <div style="text-align: center;">
              <div style="font-size: 24px; color: #409EFF; font-weight: bold;">{{ categoryList.length }}</div>
              <div style="color: #909399; font-size: 12px;">总分类数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div style="text-align: center;">
              <div style="font-size: 24px; color: #67C23A; font-weight: bold;">{{ selectedCategories.length }}</div>
              <div style="color: #909399; font-size: 12px;">已选分类</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div style="text-align: center;">
              <div style="font-size: 24px; color: #E6A23C; font-weight: bold;">{{ freeCount }}</div>
              <div style="color: #909399; font-size: 12px;">免费分类</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <div style="text-align: center;">
              <div style="font-size: 24px; color: #F56C6C; font-weight: bold;">{{ paidCount }}</div>
              <div style="color: #909399; font-size: 12px;">付费分类</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 已选分类显示 -->
      <div v-if="selectedCategories.length > 0" style="background: #f4f4f5; padding: 15px; border-radius: 4px; margin-bottom: 20px;">
        <div style="color: #606266; font-size: 14px; margin-bottom: 10px;">
          <i class="el-icon-collection-tag"></i> 已选择的分类
        </div>
        <el-tag
          v-for="catId in selectedCategories"
          :key="catId"
          closable
          @close="toggleCategory(catId)"
          style="margin-right: 10px; margin-bottom: 5px;"
        >
          {{ getCategoryName(catId) }}
        </el-tag>
      </div>

      <!-- 分类选择网格 -->
      <el-row :gutter="15">
        <el-col :span="6" v-for="category in categoryList" :key="category.categoryId">
          <el-card 
            :body-style="{ padding: '15px', cursor: 'pointer' }"
            shadow="hover"
            :class="{ 'category-selected': selectedCategories.includes(category.categoryId) }"
            @click.native="toggleCategory(category.categoryId)"
            style="margin-bottom: 15px;"
          >
            <div style="text-align: center;">
              <div style="font-size: 32px; margin-bottom: 8px;">{{ category.categoryIcon }}</div>
              <div style="font-weight: bold; margin-bottom: 5px;">{{ category.categoryName }}</div>
              <div style="font-size: 12px; color: #909399;">
                {{ category.videoCount }} 个视频
              </div>
              <el-tag v-if="category.isFree === 1" type="success" size="mini" style="margin-top: 5px;">免费</el-tag>
              <el-tag v-else type="warning" size="mini" style="margin-top: 5px;">付费</el-tag>
            </div>
            <div v-if="selectedCategories.includes(category.categoryId)" class="selected-mark">✓</div>
          </el-card>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="bindOpen = false">取 消</el-button>
        <el-button type="warning" @click="selectedCategories = []">清空选择</el-button>
        <el-button type="primary" @click="submitBind">确定绑定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChannel, getChannel, delChannel, addChannel, updateChannel, getChannelCategories, bindCategories } from "@/api/video/channel";
import { listCategory } from "@/api/video/category";

export default {
  name: "Channel",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通道表格数据
      channelList: [],
      // 分类列表
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 绑定分类对话框
      bindOpen: false,
      // 当前通道
      currentChannel: {},
      // 已选分类
      selectedCategories: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channelName: null,
        channelType: null,
        isVisible: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        channelName: [
          { required: true, message: "通道名称不能为空", trigger: "blur" }
        ],
        channelType: [
          { required: true, message: "通道类型不能为空", trigger: "change" }
        ],
        sortOrder: [
          { required: true, message: "排序权重不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    freeCount() {
      return this.selectedCategories.filter(id => {
        const cat = this.categoryList.find(c => c.categoryId === id);
        return cat && cat.isFree === 1;
      }).length;
    },
    paidCount() {
      return this.selectedCategories.length - this.freeCount;
    }
  },
  created() {
    this.getList();
    this.getCategoryList();
  },
  methods: {
    /** 查询通道列表 */
    getList() {
      this.loading = true;
      listChannel(this.queryParams).then(response => {
        this.channelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询分类列表 */
    getCategoryList() {
      listCategory({}).then(response => {
        this.categoryList = response.rows || [];
      });
    },
    /** 格式化数字 */
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
      }
      return num;
    },
    /** 获取分类名称 */
    getCategoryName(categoryId) {
      const cat = this.categoryList.find(c => c.categoryId === categoryId);
      return cat ? `${cat.categoryIcon} ${cat.categoryName}` : categoryId;
    },
    /** 切换分类选择 */
    toggleCategory(categoryId) {
      const index = this.selectedCategories.indexOf(categoryId);
      if (index > -1) {
        this.selectedCategories.splice(index, 1);
      } else {
        this.selectedCategories.push(categoryId);
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        channelId: null,
        channelName: null,
        channelSubtitle: null,
        channelDescription: null,
        channelIcon: "💜",
        channelType: "mixed",
        sortOrder: 0,
        isVisible: 1,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.channelId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通道配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const channelId = row.channelId || this.ids
      getChannel(channelId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改通道配置";
      });
    },
    /** 绑定分类操作 */
    handleBindCategory(row) {
      this.currentChannel = row;
      this.bindOpen = true;
      // 加载已绑定的分类
      getChannelCategories(row.channelId).then(response => {
        this.selectedCategories = response.data || [];
      });
    },
    /** 提交绑定 */
    submitBind() {
      bindCategories(this.currentChannel.channelId, this.selectedCategories).then(response => {
        this.$modal.msgSuccess("绑定成功");
        this.bindOpen = false;
        this.getList();
      });
    },
    /** 状态切换 */
    handleStatusChange(row) {
      let text = row.isVisible === 1 ? "显示" : "隐藏";
      this.$modal.confirm('确认要将通道"' + row.channelName + '"设置为' + text + '状态吗？').then(function() {
        return updateChannel(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isVisible = row.isVisible === 0 ? 1 : 0;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.channelId != null) {
            updateChannel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChannel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const channelIds = row.channelId || this.ids;
      this.$modal.confirm('是否确认删除通道编号为"' + channelIds + '"的数据项？').then(function() {
        return delChannel(channelIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.category-selected {
  border: 2px solid #409EFF;
  background: #ecf5ff;
}
.selected-mark {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  background: #409EFF;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
}
</style>

